/**
 * Copyright (c) 2010 Simple Graph Tools contributors. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * $Id$
 */
package org.sgt.coredef.util;

import java.util.Set;

import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.sgt.coredef.Chain;
import org.sgt.coredef.Graph;
import org.sgt.coredef.Node;

/**
 * @author Anne BUTTIGHOFFER
 * 
 */
public class GraphHelper {

	/**
	 * Caches the {@link Graph} to handle.
	 */
	private Graph myGraph;

	/**
	 * Caches the {@link IGraphWalkerPolicy} used by this helper.
	 */
	private GraphWalker walker;

	/**
	 * Constructor.
	 * @param graph {@link Graph} to handle.
	 * @param walkerPolicy {@link IGraphWalkerPolicy} used by this helper.
	 */
	public GraphHelper(final Graph graph
			, final IGraphWalkerPolicy walkerPolicy) {
		myGraph = graph;
		walker = new GraphWalker(graph);
		walker.setPolicy(walkerPolicy);
	}

	/**
	 * @return The handled {@link Graph}.
	 */
	public final Graph getGaph() {
		return myGraph;
	}

	/**
	 * @return The {@link IGraphWalkerPolicy} used by this helper.
	 */
	public final GraphWalker getWalker() {
		return walker;
	}

	/**
	 * Builds All possible Chains in the current graph which have given Nodes as
	 * source and destination.
	 * 
	 * @param startNode
	 *            {@link Node}.
	 * @param endNode
	 *            {@link Node}.
	 * @return the list of all possible chains (may be empty but not null).
	 */
	public final EList<Chain> buildChains(final Node startNode
			, final Node endNode) {
		EList<Chain> chains = new BasicEList<Chain>();
		if (myGraph.getNodes().contains(startNode)
				&& myGraph.getNodes().contains(endNode)) {
			Route route = new Route(startNode, endNode);
			Set<Chain> gChains = walker.getChains(route);
			if (gChains == null) {
				walker.updateChains(route);
				gChains = walker.getChains(route);
			}
			chains.addAll(gChains);
		}
		return chains;
	}

	
}
